Edit Distance
LeetCode 72 | Difficulty: Mediumβ
MediumProblem Descriptionβ
Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2.
You have the following three operations permitted on a word:
- Insert a character
- Delete a character
- Replace a character
Example 1:
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')
Example 2:
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')
Constraints:
- `0 <= word1.length, word2.length <= 500`
- `word1` and `word2` consist of lowercase English letters.
Topics: String, Dynamic Programming
Approachβ
Dynamic Programmingβ
Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.
Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 104 ms)β
| Metric | Value |
|---|---|
| Runtime | 104 ms |
| Memory | N/A |
| Date | 2018-03-05 |
public class Solution {
public int MinDistance(string word1, string word2) {
int m=word1.Length, n=word2.Length;
int[,] dp = new int[m+1,n+1];
for (int i = 0; i <= m; i++)
{
dp[i,0] = i;
}
for (int j = 0; j <= n; j++)
{
dp[0,j] = j;
}
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
if(word1[i-1]==word2[j-1])
{
dp[i,j] = dp[i-1,j-1];
}
else
{
dp[i, j] = Math.Min(Math.Min(dp[i - 1, j - 1] + 1, dp[i, j - 1]+1 ), dp[i - 1, j]+1);
}
}
}
return dp[m,n];
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| DP (2D) | $O(n Γ m)$ | $O(n Γ m)$ |
Interview Tipsβ
- Discuss the brute force approach first, then optimize. Explain your thought process.
- Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
- Consider if you can reduce space by only keeping the last row/few values.